package test.order.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import test.api.common.RequestVo;
import test.api.common.ResponseVo;
import test.order.api.OrderApi;
import test.order.api.vo.OrderVo;

import java.util.Date;
import java.util.UUID;

/**
 * Created by huang on 2018/2/6.
 */
@Component
@Service(interfaceClass = OrderApi.class)
@Transactional(readOnly = true)
public class OrderApiImpl implements OrderApi {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    public ResponseVo<OrderVo> orderInfo(String orderNo) {
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public ResponseVo<OrderVo> createOrder(RequestVo<OrderVo> requestVo) {
        ResponseVo<OrderVo> responseVo = new ResponseVo<OrderVo>();

        //模拟生成订单
        final OrderVo orderVo = new OrderVo();
        orderVo.setCreatedDate(new Date());
        orderVo.setOrderId(UUID.randomUUID().toString());
        orderVo.setProductId(UUID.randomUUID().toString());
        orderVo.setProductName("iphone x ");

        responseVo.setResponse(orderVo);
        responseVo.setMessage("success");
        responseVo.setResultCode(200);

        //订单生成后回写相关任务到mq中
        /*jmsTemplate.send("order_created", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                String message = String.format("order created ,id: %s",orderVo.getOrderId());
                ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
                activeMQTextMessage.setText(message);
                activeMQTextMessage.setMessageId(new MessageId(orderVo.getOrderId(),System.currentTimeMillis()));
                return activeMQTextMessage;
            }
        });*/

        jmsTemplate.convertAndSend("order_created",orderVo);

        return responseVo;
    }

    @Override
    public ResponseVo<OrderVo> updateOrder(RequestVo<OrderVo> requestVo) {
        return null;
    }
}
